<template>
  <div class="game-conatiner">
    <audio controls="true" autoplay="true" name="media" loop="true" hidden="true">
      <source src="../../../assets/audio/玩玩小游戏.mp3" type="audio/mpeg" />
    </audio>
    <div class="game-conatiner-box">
      <Header :isTransBg="true" :isGoBack="false">
        <template v-slot:left>
          <span>翻翻乐</span>
        </template>
        <template v-slot:center>
          <div class="time">
            <span v-if="isWatch"> 查看时间：{{ watchTime | filterTime(0, "m") }} </span>
            <span v-if="isGame"> 游戏时间：{{ gameTime | filterTime(0, "m") }} </span>
          </div>
          <div class="lightning-list">
            <span>体力：</span>
            <div class="lightning-item" v-for="index in lightnNum" :key="index">
              <img src="@/assets/img/icon-lightning.png" alt="" />
            </div>
            <div
              class="lightning-item lightning-item-gray"
              v-for="index in 5 - lightnNum"
              :key="'gray' + index"
            >
              <img src="@/assets/img/icon-lightning-gray.png" alt="" />
            </div>
          </div>
          <div class="difficulty ml10" v-if="isWatch || isGame">
            <span> 当前难度：{{ difficultyObj[difficulty] }} </span>
          </div>
          <div class="difficulty ml10">
            <span> 当前积分：{{ passCardNum + oldPassCardNum }} </span>
          </div>
        </template>
        <template v-slot:right>
          <div class="close-memeory" @click="goStudyIndex">
            关闭
            <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
          </div>
        </template>
      </Header>
      <div class="w1200 card-list-coantiner" id="card-list-coantiner">
        <div class="card-list">
          <div class="card-list-line" v-for="(cards, listIndex) in cardList" :key="listIndex">
            <div
              class="card-list-column"
              v-for="(card, index) in cards"
              :key="card.word_id + '-' + difficulty + '-' + passNum + '-' + listIndex + '-' + index"
            >
              <Crad
                :cardWidth="cardWidth"
                :cardHeight="cardHeight"
                :cardData="card"
                :listIndex="listIndex"
                :index="index"
                :ref="`card-${listIndex}-${index}`"
                @flipCard="
                  (frontOrBack, cardData) => {
                    flipCard(listIndex, index, frontOrBack, cardData);
                  }
                "
              ></Crad>
            </div>
          </div>
        </div>
      </div>
    </div>
    <CheckedDialog :wordNum="wordNum" @startGame="getChecked" ref="checkedDialog"></CheckedDialog>
  </div>
</template>
<script>
import Header from "@/components/Header";
import Crad from "./Card";
import { getWordList, postGameResult, getWordNum, decreaseEnergy } from "@/api/game";
import CheckedDialog from "./CheckedDialog";
const matrixList = [
  {
    totalNumber: 12,
    lineNumber: 3,
    columnNumber: 4,
  },
  {
    totalNumber: 20,
    lineNumber: 4,
    columnNumber: 5,
  },
  {
    totalNumber: 30,
    lineNumber: 5,
    columnNumber: 6,
  },
  {
    totalNumber: 42,
    lineNumber: 6,
    columnNumber: 7,
  },
  {
    totalNumber: 56,
    lineNumber: 7,
    columnNumber: 8,
  },
  {
    totalNumber: 72,
    lineNumber: 8,
    columnNumber: 9,
  },
];
const imgWidth = 140;
const imgHeight = 174;
// const animation_duration = 1;
export default {
  data() {
    return {
      difficulty: 1,
      passNum: 0,
      type: 4,
      cardList: [],
      wordData: {
        game_time: 0, //游戏时间
        examine: 0, //查看时间
      },
      lineNumber: 0,
      columnNumber: 0,
      cardWidth: 0,
      cardHeight: 0,
      checkedCard: [],
      timer: null,
      watchTime: 0,
      gameTime: 0,
      isWatch: false,
      isGame: false,
      lightnNum: 0, //体力
      passCardNum: 0, //当前消掉的卡牌对数
      oldPassCardNum: 0, //历史消掉的卡牌对数
      wordNum: {
        totalNumber: 0,
        newWord: 0,
        knowWord: 0,
        studyWord: 0,
      },
      difficultyObj: {
        1: "简单",
        2: "中等",
        3: "困难",
        4: "专家",
        5: "大师",
        6: "特级大师",
      },
    };
  },
  methods: {
    // 开始游戏
    getChecked(data) {
      this.oldPassCardNum = 0;
      this.type = data.type;
      this.difficulty = data.difficulty;
      if (this.lightnNum > 0) {
        this.decreaseEnergy();
        this.getWordList();
      } else {
        this.$alert("体力不足，请稍后再试哦~", "消息提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.goStudyIndex();
          },
        });
      }
    },
    goStudyIndex() {
      this.$router.push({
        name: "studyIndex",
      });
    },
    // 获取单词列表
    getWordList() {
      let params = {
        type: this.type,
        difficulty: this.difficulty,
      };
      getWordList(params).then((res) => {
        if (res.code == 200 && res.data && res.data.game_volist) {
          this.wordData = res.data;
          this.watchTime = this.wordData.examine;
          this.gameTime = this.wordData.game_time;
          let cardList = [];
          this.wordData.game_volist.forEach((word) => {
            cardList.push({
              word_id: word.word_id,
              word_name: word.word_name,
            });
            cardList.push({
              word_id: word.word_id,
              paraphrase: word.list[0],
            });
          });
          this.setCardList(cardList);
          return;
        }
        if (res.data == 0) {
          this.$alert("体力不足，请稍后再试哦~", "消息提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.goStudyIndex();
            },
          });
        }
        if (!res.data.game_volist) {
          this.$alert("没有查询到可用单词", "消息提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.goStudyIndex();
            },
          });
        }
      });
    },
    // 根据获取的单词处理卡牌（cardList,cardWidth,cardHeight,lineNumber,columnNumber）
    setCardList(cardList) {
      let totalNumber = cardList.length;
      let columnNumber = 0;
      let lineNumber = 0;
      let matrixIndex = matrixList.findIndex((item) => {
        return totalNumber <= item.totalNumber;
      });
      if (matrixIndex != -1) {
        columnNumber = matrixList[matrixIndex].columnNumber; //列数
        lineNumber = matrixList[matrixIndex].lineNumber; //行数
      } else {
        throw new Error(`${totalNumber}没有合适的矩阵模板`);
      }
      //   总宽度1200
      let containerHeight = document.getElementById("card-list-coantiner").offsetHeight;
      let containerWidth = document.getElementById("card-list-coantiner").offsetWidth;
      let cardWidth = containerWidth / columnNumber;
      let cardHeight = containerHeight / lineNumber;
      cardWidth > imgWidth ? (cardWidth = imgWidth) : false;
      cardHeight > imgHeight ? (cardHeight = imgHeight) : false;
      let cardWidth1 = cardHeight / (imgHeight / imgWidth);
      if (cardWidth1 > cardWidth) {
        console.log(cardHeight);
      } else {
        cardWidth = cardWidth1;
      }
      this.columnNumber = columnNumber;
      this.lineNumber = lineNumber;
      this.cardWidth = cardWidth;
      this.cardHeight = cardHeight;
      cardList = this._.shuffle(cardList);
      this.cardList = this._.chunk(cardList, columnNumber);
      this.$nextTick(() => {
        this.startWatch();
      });
    },
    // 查看时间的倒计时
    startWatch() {
      this.isWatch = true;
      this.timer = setInterval(() => {
        this.watchTime--;
        if (this.watchTime <= 0) {
          clearInterval(this.timer);
          this.isWatch = false;
          this.hiddenAllCard();
          this.startGame();
        }
      }, 1000);
    },
    // 游戏时间的倒计时
    startGame() {
      this.isGame = true;
      //   this.gameTime = 10 * 60;
      this.timer = setInterval(() => {
        this.gameTime--;
        if (this.gameTime <= 0) {
          this.isGame = false;
          clearInterval(this.timer);
          this.postGameResult(0);
          let openTimer = setTimeout(() => {
            this.cardList = [];
            this.oldPassCardNum += this.passCardNum;
            this.passCardNum = 0;
            this.$refs.checkedDialog.openDialog();
            clearInterval(openTimer);
          }, 500);
          //   游戏结束
        }
      }, 1000);
    },
    // 翻过去所有的卡牌
    hiddenAllCard() {
      this.cardList.forEach((cards, listIndex) => {
        cards.forEach((card, index) => {
          this.hiddenOneCard(listIndex, index);
        });
      });
    },
    // 翻过去某一张卡牌
    hiddenOneCard(listIndex, index) {
      if (this.$refs[`card-${listIndex}-${index}`] && this.$refs[`card-${listIndex}-${index}`][0]) {
        this.$refs[`card-${listIndex}-${index}`][0].backCard();
        console.log("成功翻过去,坐标", listIndex, index);
        this.removeCheckedCard(listIndex, index);
      }
    },
    // 调用成功消除的动画
    successOneCard(listIndex, index) {
      if (this.$refs[`card-${listIndex}-${index}`] && this.$refs[`card-${listIndex}-${index}`][0]) {
        this.$refs[`card-${listIndex}-${index}`][0].matchSuccess();
        console.log("成功消除,坐标", listIndex, index);
        this.removeCheckedCard(listIndex, index);
      }
    },
    // 判断是不是最后一张牌
    isLastCard() {
      let flag = true;
      this.cardList.forEach((cards, listIndex) => {
        cards.forEach((card, index) => {
          if (
            this.$refs[`card-${listIndex}-${index}`] &&
            this.$refs[`card-${listIndex}-${index}`][0] &&
            this.$refs[`card-${listIndex}-${index}`][0].successBtn == false
          ) {
            flag = false;
          }
        });
      });
      if (flag) {
        //   游戏通过
        clearInterval(this.timer);
        this.isGame = false;
        // 下一局;
        this.postGameResult(1);
        let listTimer = setTimeout(() => {
          this.cardList = [];
          this.oldPassCardNum += this.passCardNum;
          this.passCardNum = 0;
          this.passNum++;
          if (this.passNum >= this.difficulty + 1 && this.difficulty < 6) {
            this.passNum = 0;
            this.difficulty++;
          }
          this.getWordList();
          clearTimeout(listTimer);
        }, 1000);
      }
    },
    // 判断有没有需要消除的或者反回去的
    isSuccess() {
      console.log(this.checkedCard);
      if (this.checkedCard.length > 1) {
        let data1 = this.checkedCard[0];
        let data2 = this.checkedCard[1];
        if (data1.wordData.word_id == data2.wordData.word_id) {
          this.successOneCard(data1.listIndex, data1.index);
          this.successOneCard(data2.listIndex, data2.index);
          // 判断是不是最后一组
          this.passCardNum++;
          this.isLastCard();
        } else {
          // 两个都翻回去
          this.hiddenOneCard(data1.listIndex, data1.index);
          this.hiddenOneCard(data2.listIndex, data2.index);
          console.log("对不上翻回去,坐标", data1.listIndex, data1.index);
          console.log("对不上翻回去,坐标", data2.listIndex, data2.index);
        }
      }
    },
    // card翻牌的回调
    flipCard(listIndex, index, frontOrBack, wordData) {
      if (frontOrBack) {
        // 翻开
        let cardIndex = this.checkedCard.findIndex((item) => {
          return item.listIndex == listIndex && item.index == index;
        });
        console.log("点击翻开,坐标", listIndex, index);
        if (cardIndex == -1) {
          this.checkedCard.push({
            listIndex,
            index,
            wordData,
          });
          this.isSuccess();
        } else {
          debugger;
        }
      } else {
        //合上
        console.log("点击翻回去,坐标", listIndex, index);
        this.removeCheckedCard(listIndex, index);
      }
      console.log("当前翻开的卡片", this.checkedCard);
    },
    removeCheckedCard(listIndex, index) {
      let cradIndex = this.checkedCard.findIndex((item) => {
        return item.listIndex == listIndex && item.index == index;
      });
      if (cradIndex >= 0) {
        this.checkedCard.splice(cradIndex, 1);
      }
    },
    //提交每一小局的游戏结果
    postGameResult(isTrue) {
      let params = {
        testTime: this.wordData.game_time - this.gameTime,
        grade: this.passCardNum,
        isTrue,
        id: this.wordData.id,
        classify: 1,
      };
      console.log("ok", params);
      postGameResult(params).then((res) => {
        if (res.code == 200) {
          //   this.getWordNum();
          console.log(res.data);
        }
      });
    },
    // 获取当前体力
    getWordNum() {
      getWordNum().then((res) => {
        if (res.code == 200 && res.data) {
          this.wordNum.totalNumber = res.data.wordNumber;
          this.wordNum.newWord = res.data.a2;
          this.wordNum.knowWord = res.data.a1;
          this.wordNum.studyWord = res.data.a1 + res.data.a2;
          this.lightnNum = res.data.energy;
        }
      });
    },
    // 减体力
    decreaseEnergy() {
      decreaseEnergy().then((res) => {
        if (res.code == 200) {
          this.getWordNum();
        }
      });
    },
  },
  created() {
    this.getWordNum();
    this.$bus.$on("addEnergy", () => {
      this.getWordNum();
    });
  },
  components: {
    Header,
    Crad,
    CheckedDialog,
  },
};
</script>
